import scrapy, time, hashlib, json
from urllib.parse import urlencode


class A1688Spider(scrapy.Spider):
    name = "a1688"

    app_key = "12574478"
    secret = "d272586e5935d67f"

    def start_requests(self):
        t = str(int(time.time() * 1000))
        data_str = (
            '{"appId":32517,'
            '"params":"{\\"verticalProductFlag\\":\\"pcmarket\\",'
            '\\"searchScene\\":\\"pcOfferSearch\\",'
            '\\"charset\\":\\"utf8\\",'
            '\\"beginPage\\":1,'
            '\\"pageSize\\":60,'
            '\\"keywords\\":\\"男装\\",'
            '\\"spm\\":\\"a260k.home2025.category.dL2.66333597p3eumR\\",'
            '\\"method\\":\\"getOfferList\\"}"}'
        )
        sign = hashlib.md5(
            (self.app_key + t + data_str + self.secret).encode()
        ).hexdigest()

        url = (
            "https://h5api.m.1688.com/h5/mtop.relationrecommend.wirelessrecommend.recommend/2.0/?"
            + urlencode(
                {
                    "jsv": "2.7.4",
                    "appKey": self.app_key,
                    "t": t,
                    "sign": sign,
                    "api": "mtop.relationrecommend.WirelessRecommend.recommend",
                    "v": "2.0",
                    "dataType": "jsonp",
                    "jsonpIncPrefix": "fetchTpp_32517_getOfferList",
                    "type": "jsonp",
                    "callback": "mtopjsonpfetchTpp_32517_getOfferList3",
                    "data": data_str,
                }
            )
        )

        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
            "Referer": "https://s.1688.com/",
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.9",
        }
        cookies = {
            "_m_h5_tk": "fce247b6d60ed2eae41942064ec84499_1762788999374",  # ← 刚刚复制的
            "_m_h5_tk_enc": "e99a192f1ed88660b5e2a7e36253f711",  # ← 同上
        }

        yield scrapy.Request(url, headers=headers, cookies=cookies, callback=self.parse)

    def parse(self, response):
        print(response.text[:600])
